package biolabs.visual.j3d;

import java.awt.Component;

import javax.media.j3d.AmbientLight;
import javax.media.j3d.Background;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.Light;
import javax.media.j3d.Node;
import javax.media.j3d.View;
import javax.vecmath.Color3f;

import biolabs.gui.WindowSink;

import com.sun.j3d.utils.universe.SimpleUniverse;

public class Java3DWindowSink extends WindowSink<Node> {

	private final Canvas3D canvas;
	private final SimpleUniverse universe;

	private BranchGroup currentScene = null;
	private final Light light = new AmbientLight(new Color3f(1, 1, 1));
	private final Background background = new Background(new Color3f(1, 1, 1));

	public Java3DWindowSink() {
		canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
		universe = new SimpleUniverse(canvas);
		universe.getViewingPlatform().setNominalViewingTransform();
		universe.getViewingPlatform().getViewPlatform().setViewAttachPolicy(View.NOMINAL_SCREEN);
	}

	@Override
	public void push(long time, Node scene) {
		if(currentScene != null) {
			universe.getLocale().removeBranchGraph(currentScene);
			currentScene.removeAllChildren();
		}
		currentScene = new BranchGroup();
		currentScene.setCapability(BranchGroup.ALLOW_DETACH);
		background.setApplicationBounds(scene.getBounds());
		light.setInfluencingBounds(scene.getBounds());
		currentScene.addChild(background);
		currentScene.addChild(light);
		currentScene.addChild(scene);
		universe.addBranchGraph(currentScene);
	}

	@Override
	public void flush() {
		// do nothing
	}

	@Override
	public void close() {
		universe.cleanup();
		super.close();
	}

	@Override
	public Component getContent() {
		return canvas;
	}

}
